<template>
  <div>
    <!-- 显示数据 -->
    <el-card class="box-card">
      <!-- 按钮 -->
      <el-button
        type="primary"
        icon="Plus"
        @click="addTardeMark"
        v-has="`btn.Trademark.add`"
        >添加品牌</el-button
      >
      <!-- 表格 -->
      <el-table border style="margin: 10px 0px" :data="trademarkArr">
        <el-table-column
          label="序号"
          width="80"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTradeMark(row)"
              v-has="`btn.Trademark.update`"
            ></el-button>

            <el-popconfirm
              :title="`确定删除${row.tmName}吗?`"
              width="200px"
              icon="Delete"
              @confirm="removeTradeMarK(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="Delete"
                  v-has="`btn.Trademark.remove`"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器
      current-page 当前页数
      page-size 每页显示多少条数据
      page-sizes 每页显示个数选择器的选项设置
      background 是否为分页按钮添加背景色
      layout 组件布局，子组件名用逗号分隔
      current-change当前页发生改变时会触发
      size-change每页显示条数发生改变时会触发
      total 总条数
    -->
      <el-pagination
        v-model:current-page="PageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="changePage"
        @size-change="changelimit"
      ></el-pagination>
    </el-card>
    <!-- 对话框组件
    v-model 绑定值,用来控制对话框的显示与隐藏
    title 对话框的标题
  -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkInfo.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkInfo"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称:" label-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkInfo.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO:" label-width="100px" prop="logoUrl">
          <!-- 
            before-upload图片上传之前的回调，用于判断文件大小，类型
            on-success 图片上传之后的回调，可以收集图片的路径
           -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="trademarkInfo.logoUrl"
              :src="trademarkInfo.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import { getProDuctInfo } from "@/api/produck/trademark";
import type {
  Records,
  TardeMarkData,
  TardeMark,
} from "@/api/produck/trademark/type";
import { ElMessage, type UploadProps } from "element-plus";
import { addOrUpdateTradeMark, deleteTradeMark } from "@/api/produck/trademark";
let formRef = ref();
let PageNo = ref<number>(1);
let limit = ref<number>(3);
let total = ref<number>(0);
let trademarkArr = ref<Records>([]);
//控制对话框的显示与隐藏
let dialogFormVisible = ref<boolean>(false);
//收集品牌信息
let trademarkInfo = reactive<TardeMark>({
  tmName: "",
  logoUrl: "",
});
// 获取数据
const HasTradeMarke = async () => {
  let reslut: TardeMarkData = await getProDuctInfo(PageNo.value, limit.value);
  if (reslut.code == 200) {
    total.value = reslut.data.total;
    trademarkArr.value = reslut.data.records;
  }
};

onMounted(() => {
  HasTradeMarke();
});
//当页码发生改变时触发的回调
const changePage = () => {
  //再次调用函数获取数据
  HasTradeMarke();
};
//每页显示条数发生改变时会触发
const changelimit = () => {
  //让页码数为第一页
  PageNo.value = 1;
  //再次调用函数获取数据
  HasTradeMarke();
};
//添加品牌的回调
const addTardeMark = () => {
  //将在对话框输入的数据清除
  trademarkInfo.tmName = "";
  trademarkInfo.logoUrl = "";
  trademarkInfo.id = 0;
  //让对话框显示
  dialogFormVisible.value = true;
  nextTick(() => {
    //等待组件加载完毕之后再清除表单验证
    formRef.value.clearValidate();
  });
};
//修改品牌的回调
const updateTradeMark = async (row: TardeMark) => {
  //将tmName和logoUrl从row里面解构出来
  let { tmName, logoUrl, id } = row;
  // 将解构出来的数据复制给tradmarkInfo
  trademarkInfo.tmName = tmName;
  trademarkInfo.logoUrl = logoUrl;
  trademarkInfo.id = id;
  nextTick(() => {
    //等待组件加载完毕之后再清除表单验证
    formRef.value.clearValidate();
  });

  //让对话框隐藏
  dialogFormVisible.value = true;
};
//取消按钮的回调
const cancel = () => {
  //让对话框隐藏
  dialogFormVisible.value = false;
  //将在对话框输入的数据清除
  trademarkInfo.tmName = "";
  trademarkInfo.logoUrl = "";
};
//确定按钮的回调
const confirm = async () => {
  //给整个表单进行验证，成功了才能执行下面的代码
  await formRef.value.validate();
  let reslut = await addOrUpdateTradeMark(trademarkInfo);
  if (reslut.code == 200) {
    ElMessage({
      type: "success",
      message: `${trademarkInfo.id ? "修改成功" : "添加成功"}`,
    });
    if (!trademarkInfo.id) {
      PageNo.value = 1;
    }
  } else {
    ElMessage({
      type: "error",
      message: `${trademarkInfo.id ? "修改失败" : "添加失败"}`,
    });
  }

  dialogFormVisible.value = false;
  //再次调用获取信息的函数
  HasTradeMarke();
};
//上传图片之前的回调,用于约束文件类型，大小
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      ElMessage({
        type: "success",
        message: "上传成功",
      });
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传图片大小不能超过 4MB!",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传图片只能是 JPG 或 PNG 或 gif 格式!",
    });
    return false;
  }
};
//上传图片之后的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
) => {
  //解决冒红光问题，无需关注
  if (1 > 2) {
    console.log(uploadFile);
  }
  //收集数据
  trademarkInfo.logoUrl = response.data;
  //清除表单验证
  formRef.value.clearValidate("logoUrl");
};
//校验规则函数(文本)
const validatorNames = (rule: any, value: any, callBack: any) => {
  //解决冒红光问题，无需关注
  if (1 > 2) {
    console.log(rule);
  }
  //rule规则对象，value文本值，callback放行函数
  //如果去掉空格的文本值长度小于2位
  if (value.trim().length < 2) {
    //调用回调函数，返回错误信息
    callBack(new Error("品牌名称不能少于两位"));
  } else {
    //否则，放行
    callBack();
  }
};
//校验规则函数(图片)
const validatorlogo = (rule: any, value: any, callBack: any) => {
  //解决冒红光问题，无需关注
  if (1 > 2) {
    console.log(rule);
  }
  if (value) {
    callBack();
  } else {
    callBack(new Error("请上传品牌logo"));
  }
};
const rules = {
  tmName: [
    {
      required: true,
      //自定义规则校验
      validator: validatorNames,
      //触发时机
      trigger: "change",
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorlogo,
      trigger: "change",
    },
  ],
};
//气泡删除确认按钮的回调
const removeTradeMarK = async (id: number) => {
  let result = await deleteTradeMark(id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    //如果当前页数数据条数小于1的话，就返回上一页
    if (trademarkArr.value.length < 1) {
      PageNo.value = PageNo.value - 1;
    }
    //重新获取数据
    HasTradeMarke();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
